//
//  NewContactDelegate.m
//  IWeighMyself
//
//  Created by Francisco Gindre on 8/10/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "NewContactDelegate.h"


@implementation NewContactDelegate

@synthesize newContact;

- (void)newPersonViewController:(ABNewPersonViewController *)newPersonViewController didCompleteWithNewPerson:(ABRecordRef)person{
	
	NSLog(@"didCompleteWithNewPerson");
	if (person!=nil){
		
		
		
		/*
		 create the new Contact
		 */
		
		self.newContact = [NSMutableDictionary dictionaryWithCapacity: 2];
		
		NSString* name = (NSString *)ABRecordCopyValue(person,
													   kABPersonFirstNameProperty);
		[name retain];
		/*
         get email multi value array
         */
        
        ABMultiValueRef emailList = ABRecordCopyValue(person, kABPersonEmailProperty);
        
        /*
         get the selected record
         */
		
		NSLog(@"fetched emailList %@",emailList);
		
        NSString *email= (NSString*) ABMultiValueCopyValueAtIndex(emailList, 0);
		
		[email retain];
		
		[self.newContact setObject:name forKey:@"DefaultContactName"];
		
		[self.newContact setObject:email forKey:@"DefaultContactEmail"];
		
		
		
		NSLog(@"new default contact will be %@",self.newContact);
		
		
		/*
		 release some memory
		 */
		
		[email release];
		[name release];
		
		/*
		 ask the user whether he/she prefers to add this contact as default contact
		 */
		UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"NewContactCreatedAlertTitle",@"")
												message:NSLocalizedString(@"NewContactCreatedAlertMessage",@"")
												delegate:self
												cancelButtonTitle:NSLocalizedString(@"NewContactCreatedAlertCancel",@"") 
												otherButtonTitles:NSLocalizedString(@"NewContactCreatedAlertYes",@""),nil];
		[alert show];
	}
	
	/*
	 somehow modal presentation did not show navigation bar, so it was presented as a normal view controller,
	 so it is presented as a viewController being pushed.
	 */
	[newPersonViewController.navigationController popViewControllerAnimated:YES];
	
		
}

- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person 
					property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifierForValue {
	return NO;
}

/*
Sent to the delegate after an alert view is dismissed from the screen.
*/

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
	
	NSLog(@"button index is %d",buttonIndex );
	if (buttonIndex == 1) {
		IWeighMyselfAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
		
		[appDelegate retain];
		[appDelegate.plistXML setObject:self.newContact forKey:@"DefaultContact"];
		
	}
	
	
	
}

@end
